# -*- coding: utf-8 -*-
import time

import faker
from selenium import webdriver
from selenium.common import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec

# 登陆的账号，注册了作者，发布过小说
driver = webdriver.Chrome()  # 实例化浏览器对象
driver.maximize_window()
wait = WebDriverWait(driver, 5)  # 实例化等待对象
login_url = "http://120.25.127.201:18001/user/login.html"
driver.get(login_url)  # 在新的窗口打开url
username="15574113907"
password="123456"
el=wait.until(ec.presence_of_element_located((By.XPATH, "//input[@id='txtUName']")))
el.send_keys(username)
wait.until(ec.presence_of_element_located((By.XPATH, "//input[@id='txtPassword']"))).send_keys(password)
wait.until(ec.presence_of_element_located((By.XPATH, "//input[@id='btnLogin']"))).click()
# 根据username出现在首页作为等待条件，确保首页正常出现  你的元素的值是 15574113907  true false
wait.until(ec.text_to_be_present_in_element((By.LINK_TEXT,username),username))

# 显性等待作者专区元素并进行点击
locator = ("link text", "作家专区")
wait.until(ec.visibility_of_element_located(locator)).click()

# 切换windows窗口
handle = driver.window_handles[-1]  # 获取窗口句柄
driver.switch_to.window(handle)  # 切换窗口

# 点击章节管理
# 显性等待章节管理元素出现并进行点击
locator = ("partial link text", "章节管理")
wait.until(ec.visibility_of_element_located(locator)).click()

# 切换窗口句柄
driver.switch_to.window(driver.window_handles[-1])

try:
    # 如果有数据，点击某个元素
    locator = ("xpath", "//*[@id='hasContentDiv']/div[1]/div/a")
    wait.until(ec.visibility_of_element_located(locator)).click()
except TimeoutException:
    # 如果没有数据，点击另一个元素
    locator = ("xpath", "//*[@id='noContentDiv']/div/a")
    wait.until(ec.visibility_of_element_located(locator)).click()
except Exception:
    print("章节管理元素未找到")


# 显性等待章节名元素出现并进行输入从操作
locator = ("id", "bookIndex")
wait.until(ec.visibility_of_element_located(locator)).send_keys(f"章节名-{str(int(time.time()))}")

# 显性等待章节内容元素出现并进行输入从操作
locator = ("id", "bookContent")
wait.until(ec.visibility_of_element_located(locator)).send_keys(f"章节内容-{str(int(time.time()))}")

# 显性等待收费元素出现并点击
locator = ("css selector", '[name="isVip"][value="1"]')
wait.until(ec.visibility_of_element_located(locator)).click()

current_url = driver.current_url
# 显性等待提交元素出现并进行点击
locator = ("id", "btnRegister")
wait.until(ec.visibility_of_element_located(locator)).click()

time.sleep(5)
driver.quit()

# driver.execute_script(
#             "arguments[0].setAttribute('style',arguments[1]);",
#             el,
#             "border: 2px solid green;"  # 边框，green绿色
#         )